<?php 
/**
 * 2017年6月6日13:31:35
 * PDO SAFE
 */

// error_reporting(E_ALL);
// ini_set('display_errors', 1);

include 'common.php';



$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$deviceid = $_REQUEST['deviceid'];
$uuid = $_REQUEST['uuid'];
$androidid = $_REQUEST['androidid'];

try {
	$dbc = pdo_root_connect();

	$stmt = $dbc->prepare('select * from userinfo where username = :username and password = :password');
	$stmt->bindParam(':username', $username);
	$stmt->bindParam(':password', $password);
	$stmt->execute();
	
	if($row = $stmt->fetch()) {
		if($row['status'] == 0)
		{
			$key = md5($username."remix");
			$token = pdo_createtoken($username);
			$ip = $_SERVER['REMOTE_ADDR'];
			//成功查找到用户
			$stmt2 = $dbc->prepare('update userinfo set llip=:llip,
			uuid=:uuid,u_deviceid=:deviceid,androidid=:androidid
			,changetime=unix_timestamp(now()),token=:token 
			where username=:username and password=:password limit 1');
			//预处理
			
			$stmt2->bindParam(':llip', $ip, PDO::PARAM_STR, 12);
			$stmt2->bindParam(':uuid', $uuid, PDO::PARAM_STR, 8);
			$stmt2->bindParam(':deviceid', is_null($deviceid) ? 'NOTCLIENT' : $deviceid, PDO::PARAM_STR);
			$stmt2->bindParam(':androidid', is_null($androidid) ? 'NOTCLIENT' : $androidid, PDO::PARAM_STR);
			$stmt2->bindParam(':token', $token);
			$stmt2->bindParam(':username', $username, PDO::PARAM_STR, 16);
			$stmt2->bindParam(':password', $password, PDO::PARAM_STR, 16);
			$stmt2->execute();
			if($stmt2->rowCount() > 0){
				$errorcode = 1; //Update Token Success
				setcookie('username', $username, time() + 60*60*24*5);
				setcookie('token', $token, time() + 60*60*24*5);
			}else{
				$errorcode = 2; //Update Token Failed
			}
		}else{
			$errorcode = 5;//User Baned In Time;
		}
	}else{
		$errorcode = 3;//Not Found User
	}
}catch (PDOException $e){
	$errorcode = 4;//Other Error
	$msg = $e->getMessage();
}
echo(json_encode(array('errorcode'=>$errorcode, 'msg' => $msg, 
		'username' => $row['username'], 'nickname' => $row['nickname'],
		'token' => '')));
?>